package com.zy.je.common.mybatis.ext.model;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zy.je.common.core.constant.QueryType;
import com.zy.je.common.core.constant.StringPool;
import com.zy.je.common.core.model.QueryMap;
import com.zy.je.common.core.utils.CheckUtil;
import com.zy.je.common.mybatis.ext.util.WrapperUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查询条件增强对象--已弃用。使用QueryAndResultEnhance代替
 *
 * @author zy
 */
//@Deprecated
@Data
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
public class QueryEnhance implements IPageQuery, QueryMap {
    /**
     * 排序字段
     */
//    @ApiModelProperty(value = "排序字段")
    @TableField(exist = false)
    private String _orderBy;

    /**
     * 页码
     */
//    @ApiModelProperty(value = "页码")
    @TableField(exist = false)
    private Integer pageNo;
    /**
     * 每页数量
     */
//    @ApiModelProperty(value = "每页数量")
    @TableField(exist = false)
    private Integer pageSize;
    /**
     * 查询条件增强
     */
//    @ApiModelProperty(value = "查询条件增强")
    @TableField(exist = false)
    protected Map<String, String> _q;

    @Override
    public Map<String, String> buildQ() {
        if (null == this._q) {
            this._q = new HashMap<>();
        }
        return this._q;
    }

    @Override
    public <T> Page<T> buildPage() {
        int tmpPageNo = pageNo == null ? 1 : pageNo;
        int tmpPageSize = pageSize == null ? 10 : pageSize;
        Page<T> page = new Page<>((long) tmpPageNo, (long) tmpPageSize);
        //处理排序
        List<OrderItem> orders = WrapperUtil.fmtOrderBy2OrderItems(buildOrderBy());
        if (!CheckUtil.isBlank(orders)) {
            page.setOrders(orders);
        }
        return page;
    }

    @Override
    public String buildOrderBy() {
        String orderByKey = StringPool.UNDERSCORE + QueryType.ORDER_BY.getValue();
        for (Map.Entry<String, String> entry : buildQ().entrySet()) {
            if (entry.getKey().endsWith(orderByKey)) {
                if (!CheckUtil.isBlank(entry.getValue())) {
                    return WrapperUtil.fmtOrderBy(entry.getValue());
                }
            }
        }
        return WrapperUtil.fmtOrderBy(_orderBy);
    }

}
